package com.soulapp.hook.hooker

import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData

object RowSnapImageHook : BaseHooker() {
    private const val TAG = "RowSnapImageHook"
    private var hook: YukiMemberHookCreator.MemberHookCreator.Result? = null

    override fun getKey() = ConfigData.snapImage

    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        // val className = "cn.soulapp.android.component.chat.snapchat.SnapChatMsgBean"
        // className.toClass()
        //     .resolve()
        //     .optional()
        //     .method {
        //         modifiers(Modifiers.PUBLIC)
        //         name("getSnapChatState")
        //         emptyParameters()
        //         returnType = Int::class.javaPrimitiveType
        //     }.first()
        //     .hook {
        //         replaceTo(1)
        //     }

        val className = "cn.soulapp.android.component.chat.snapchat.SnapChatMsgBean"
        className.toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("getSnapChatState")
                emptyParameters()
                returnType = "cn.soulapp.android.component.chat.snapchat.SnapChatState".toClass()
            }
            .first()
            .apply {
                YLog.debug("[SoulHook]：hook apply $TAG ${self.name}，${self.returnType}")
            }
            .hook {
                after {
                    val resultState = result

                    YLog.debug("[SoulHook]：SnapChatState.getValue() original resultState: $resultState")
                    val stateClass =
                        "cn.soulapp.android.component.chat.snapchat.SnapChatState".toClass()

                    // 获取各个状态实例
                    val destroyedState =
                        stateClass.resolve().field { name = "DESTROYED" }.first().get()
                    val waitExchangeState =
                        stateClass.resolve().field { name = "WAIT_EXCHANGE" }.first().get()
                    val waitViewState =
                        stateClass.resolve().field { name = "WAIT_VIEW" }.first().get()

                    // 判断当前返回值是否为DESTROYED或WAIT_EXCHANGE
                    if (resultState == destroyedState || resultState == waitExchangeState) {
                        result = waitViewState
                    }
                }
            }
    }

    override fun stopHook() {
        if (hookEnabled) return
        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")
    }

}